﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace UnitTesting.Fixturing
{
	class ArrayValueProvider : IValueProvider
	{
		readonly IValueProvider _valueProvider;

		internal virtual int Count { get; set; }

		[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
		internal ArrayValueProvider(IValueProvider valueProvider)
		{
			_valueProvider = Ensure.IsNotNull(() => valueProvider);
			// ReSharper disable DoNotCallOverridableMethodsInConstructor
			Count = 3;
			// ReSharper restore DoNotCallOverridableMethodsInConstructor
		}

		public virtual object Create(Type type)
		{
			Ensure.IsNotNull(() => type);
			if (type.IsArray)
			{
				var constructor = type.GetConstructor(new[] {typeof (int)});
				// ReSharper disable PossibleNullReferenceException
				var result = (Array) constructor.Invoke(new object[] {Count});
				// ReSharper restore PossibleNullReferenceException
				Enumerable.Range(0, Count).ForEach(index => result.SetValue(_valueProvider.Create(type.GetElementType()), index));
				return result;
			}
			return NotResolved.Value;
		}
	}
}